package me.chyxion.spring.ext.view;

import java.util.Locale;
import org.slf4j.Logger;
import javax.servlet.ServletContext;
import java.net.MalformedURLException;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * @version 0.0.2
 * @since 0.0.1
 * @author chyxion <br />
 * chyxion@163.com <br />
 * Dec 5, 2014 2:33:18 PM
 */
public class InternalResourceViewResolverExt extends InternalResourceViewResolver {
	private static final Logger log = LoggerFactory.getLogger(InternalResourceViewResolverExt.class);

    @Autowired
    private ServletContext sc;

    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.view.AbstractCachingViewResolver#resolveViewName(java.lang.String, java.util.Locale)
     */
    @Override
    public View resolveViewName(String viewName, Locale locale) 
    		throws Exception {
    	return super.resolveViewName(viewName(viewName), locale);
    }

	/*
	 * (non-Javadoc)
	 * @see org.springframework.web.servlet.view.UrlBasedViewResolver#canHandle(java.lang.String, java.util.Locale)
	 */
	@Override
	protected boolean canHandle(String viewName, Locale locale) {
		try {
			// avoid 404
			return sc.getResource(getPrefix() + viewName(viewName) + getSuffix()) != null;
		}
		catch (MalformedURLException e) {
			log.warn("InternalResourceViewResolverExt#canHandle Eorror Caused.", e);
			return false;
		}
	}

	/**
	 * Process View Name
	 * @param name
	 * @return
	 */
	private String viewName(String name) {
    	return name.replaceAll("(?i)(^\\s*jsp\\:)|(\\.jsp\\s*$)", "");
	}
}
